﻿using MediatR;
using RedDragon.Common.Domain.Enterprise;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Department
{
    /// <summary>
    /// 部门树形显示
    /// </summary>
    public class SearchTreeDepartmentHandler : IRequestHandler<SearchTreeDepartmentCommand, Result>
    {
        /// <summary>
        /// 部门仓储
        /// </summary>
        private readonly IBaseRepository<Departments> _departmentRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchTreeDepartmentHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository"></param>
        /// <param name="logger"></param>
        public SearchTreeDepartmentHandler(IBaseRepository<Departments> departmentRepository,
                                           ILogger<SearchTreeDepartmentHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 部门树形显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchTreeDepartmentCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var tree = await (await _departmentRepository.GetAll()).ToTreeAsync(it => it.Children, it => it.ParentId, 0);
                //判断获取的数据不为空
                if (tree.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = tree;
                    result.Msg = "部门树形显示成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "部门树形显示异常" + ex.Message;
                _logger.LogError("部门树形显示异常" + ex.Message);
            }
            return result;
        }
    }
}
